from django_redis import get_redis_connection
from rest_framework import serializers
from oauth.models import OAuthQQUser
from users.models import User
from .utils import check_save_user_token


class QQAuthUserSerializer(serializers.Serializer):
    """QQ登录创建用户序列化器"""
    # 1,获取用户输入的绑定参数
    mobile = serializers.RegexField(regex=r'^1[3-9]\d{9}$', label='手机号')
    access_token = serializers.CharField(label='操作凭证')
    password = serializers.CharField(label='密码', min_length=8, max_length=20)
    sms_code = serializers.CharField(label='短信验证码')

    def validate(self, data):
        # 校验access_token
        access_token = data.get('access_token')
        # 获取openid
        openid = check_save_user_token(access_token)

        if not openid:
            raise serializers.ValidationError('access无效')

        # 保存openid
        data['openid'] = openid

        # 校验短信验证码
        mobile = data.get('mobile')
        sms_code = data.get('sms_code')
        # 连接redis数据库,获取
        redis = get_redis_connection('verify_code')

        # 获取真实的验证码
        real_sms_code = redis.get('sms_%s' % mobile)
        if real_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码错误')

        # 如果用户存在，检查用户密码
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            password = data.get('password')
            if not user.check_password(password):
                raise serializers.ValidationError('密码错误')
            # 保存认证后的用户
            data['user'] = user
        return data

    def create(self, validated_data):
        # 获取校验用户
        user = validated_data.get('user')
        # 如果用户不存在　则创建用户
        if not user:
            user = User.objects.create(
                username=validated_data['mobile'],
                password=validated_data['password'],
                mobile=validated_data['mobile'],
            )
            # 新增用户进行密码加密
            user.set_password(validated_data['password'])
            user.save()
            print(user.password)
        # 绑定用户ＱＱ的openid
        OAuthQQUser.objects.create(
            openid=validated_data['openid'],
            user=user
        )
        print(user)
        # 返回用户数据
        return user
